package com.jt1078.streamserver.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author: liuxiaoyan
 * @date: 2025/7/12 14:51
 */
public class JT1078FrameSplitter extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        // 假设JT1078包头为0x30316364，且每帧大小 < 64KB
        in.markReaderIndex();
        if (in.readableBytes() < 17) return;

        int frameHeader = in.readInt();
        if (frameHeader != 0x30316364) {
            // 不是JT1078帧头，丢弃
            in.resetReaderIndex();
            in.readByte();
            return;
        }
        in.resetReaderIndex();
        int frameLen = in.readableBytes();
        // 简单假设每次读入就是一帧，否则需根据协议区分长度
        byte[] data = new byte[frameLen];
        in.readBytes(data);
        out.add(ctx.alloc().buffer(data.length).writeBytes(data));
    }
}
